package com.gnuc.thoth.app;

import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.RelativeLayout;

import com.gnuc.thoth.R;
import com.gnuc.thoth.framework.Thoth;
import com.gnuc.thoth.framework.ThothLog;
import com.gnuc.thoth.framework.callbacks.ThothCallback;

public class Main extends ActivityGroup
{
	public RelativeLayout				ml			= null;
	protected LocalActivityManager	mlam		= null;
	private View							mlv		= null;
	private static Main					instance	= null;
	
	public static Main getInstance()
	{
		if (instance == null)
			instance = new Main();
		return instance;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Thoth.cx = this;
		instance = this;
		Thoth.Settings.read();
		Thoth.clearNotifications();
		try
		{
			ml = (RelativeLayout) findViewById(R.id.main_layout);
			ml.invalidate();
			mlam = (LocalActivityManager) getLocalActivityManager();
			mainHandler.sendEmptyMessage(0);
			/*
			versionCheck(new ThothCallback()
			{
				@Override
				public void handle(boolean result)
				{
					if(result)
					{
						AlertDialog.Builder adb = new AlertDialog.Builder(Thoth.cx);
						adb.setIcon(R.drawable.icon);
						adb.setMessage("Thoth needs to upgrade your application settings.");
						adb.setCancelable(false);
						adb.setPositiveButton("OK", new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog, int id)
							{
								dialog.cancel();
								mainHandler.sendEmptyMessage(0);
							}
						});
						adb.setInverseBackgroundForced(true);
						Thoth.ad = adb.create();
						WindowManager.LayoutParams lp = Thoth.ad.getWindow().getAttributes();
						lp.dimAmount = 0.1f;
						Thoth.ad.getWindow().setAttributes(lp);
						Thoth.ad.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
						Thoth.ad.show();
					}
					else
						mainHandler.sendEmptyMessage(0);
				}
			});
			*/
			Thoth.scheduleServices();
		}
		catch (Exception e)
		{
			ThothLog.e(e);
			mainHandler.sendEmptyMessage(-1);
		}
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		Thoth.Settings.write();
		if (null != Thoth.ad && Thoth.ad.isShowing())
			Thoth.ad.dismiss();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (mlam.getCurrentId().equalsIgnoreCase("SETUP_MAIN"))
				return mlam.getActivity("SETUP_MAIN").dispatchKeyEvent(event);
		}
		return false;
	}
	
	/*
	public void versionCheck(final ThothCallback callback)
	{
		try
		{
			if (!Thoth.Settings.APP_SETUP && Thoth.Settings.APP_VERSION < (getPackageManager().getPackageInfo("com.gnuc.thoth", 0)).versionCode)
			{
				Thoth.Settings.APP_SETUP = true;
				callback.handle(true);
			}
			else
				callback.handle(false);
		}
		catch (Exception nnf)
		{
			Thoth.Settings.APP_SETUP = true;
			callback.handle(true);
		}
	}
	*/
	/**
	 * The mainHandler is the core component handling inter activity communication. Switches
	 * activities based on messages passed to this handler.
	 */
	public Handler	mainHandler	= new Handler()
										{
											public void handleMessage(Message msg)
											{
												switch (msg.what)
												{
													case 0 :
													{
														if (Thoth.Settings.APP_SETUP)
															mainHandler.sendEmptyMessage(1);
														else if (Thoth.Settings.APP_UPDATE_PENDING)
														{
															if (Thoth.Settings.APP_NETWORK_CONFIGURE && Thoth.wasNetworkSwitchedOn())
															{
																Thoth.showProgressDialog(new ThothCallback()
																{
																	@Override
																	public void handle(boolean result)
																	{
																		mainHandler.sendEmptyMessage(result ? 3 : 0);
																	}
																}, false);
															}
															else if (Thoth.isNetworkOK())
																mainHandler.sendEmptyMessage(3);
															else
															{
																Thoth.switchOnNetwork(0, new ThothCallback()
																{
																	@Override
																	public void handle(boolean result)
																	{
																		mainHandler.sendEmptyMessage(result ? 3 : 1000);
																	}
																});
															}
															mainHandler.sendEmptyMessage(2);
														}
														else
															mainHandler.sendEmptyMessage(2);
														break;
													}
													case 1 :
													{
														Intent i = new Intent(Thoth.cx, SetupMain.class);
														ml.removeAllViews();
														ml.addView(getContentView("SETUP_MAIN", i));
														break;
													}
													case 2 :
													{
														Intent i = new Intent(Thoth.cx, TabMain.class);
														ml.removeAllViews();
														ml.addView(getContentView("TAB_MAIN", i));
														break;
													}
													case 3 :
													{
														Thoth.Settings.APP_UPDATE_PENDING = false;
														Thoth.Settings.write();
														Thoth.sendToService(Thoth.REQ.UPDATE_SERVER, null, null);
														break;
													}
													case -1 :
													{
														Intent i = new Intent(Thoth.cx, RescueMain.class);
														ml.removeAllViews();
														ml.addView(getContentView("RESCUE_MAIN", i));
														break;
													}
													case 666 :
													{
														finish();
														break;
													}
												}
											}
										};
	
	/**
	 * Method that creates a view attached to the passed intent. Attaches the created view to the
	 * parent view.
	 * 
	 * @param tag
	 * @param intent
	 * @return
	 */
	public View getContentView(String tag, Intent intent)
	{
		if (mlam == null)
			throw new IllegalStateException("Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?");
		final Window w = mlam.startActivity(tag, intent);
		final View wd = w != null ? w.getDecorView() : null;
		if (mlv != wd && mlv != null && mlv.getParent() != null)
			ml.removeView(mlv);
		mlv = wd;
		if (mlv != null)
		{
			mlv.setVisibility(View.VISIBLE);
			mlv.setFocusableInTouchMode(true);
			((ViewGroup) mlv).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
		}
		return mlv;
	}
}
